<?php
function  check_submit_form_bk($order_id,$total_amount,$order_description)
{
	 require_once TEMPLATEPATH ."/inc/payments/bao_kim/BaoKimPayment.php";
	$url_return=get_bloginfo('url').'payment';
	$url_cancel=get_bloginfo('url').'cancel';
	$merchant_id=get_option('merchant_id_bk');
	$secure_pass=get_option('secure_pass_bk');
	$email_bk=get_option('email_bk');
    $url_detail=get_bloginfo('url');
	$shipping_fee=0;
	$tax_fee=0;
	$baokim_url = 'https://www.baokim.vn/payment/customize_payment/order';
	$bk=new BaoKimPayment($baokim_url, $merchant_id, $secure_pass);
  	$url = $bk->createRequestUrl($order_id, $email_bk, $total_amount, $shipping_fee, $tax_fee, $order_description,$url_return, $url_cancel, $url_detail);
	echo "<script>document.location.href='$url';</script>";
	exit();
}


function update_return_from_baokim()
{
    require_once TEMPLATEPATH ."/inc/payments/bao_kim/BaoKimPayment.php";
	$baokim_url = 'https://www.baokim.vn/payment/customize_payment/order';
	$merchant_id=get_option('merchant_id_bk');
	$secure_pass=get_option('secure_pass_bk');
    $bk=new BaoKimPayment($baokim_url, $merchant_id, $secure_pass);
if(isset($_GET['checksum']) && !empty($_GET['checksum']))
{
	$arr		=	array(
		'created_on'			=>	'',
		'customer_email'		=> '',
		'customer_name'		=> '',
		'customer_phone'		=> '',
		'fee_amount'			=> '',
		'merchant_email'		=> '',
		'merchant_id'			=> '',
		'merchant_name'		=> '',
		'merchant_phone'		=> '',
		'order_id'				=> '',
		'payment_type'			=> '',
		'total_amount'			=> '',
		'transaction_id'		=> '',
		'transaction_status'	=> '',
		'checksum'				=> ''
	);

	foreach($arr as $key=>$value){
		$mang[$key]	=	isset($_GET[$key]) ? $_GET[$key] : '';
	}
	$check=$bk->verifyResponseUrl($mang);
 if($check === false)
	{
		#Tham số gửi về không hợp lệ, có sự can thiệp từ bên ngoài
		echo '<div align=\"center\">Kết quả thanh toán không hợp lệ!</div>';
	    return  ;
	}
	else
	{
		$order_id=@$_GET['order_id'];#mã order
		$total_amount=@$_GET['total_amount'];#giá sản phẩm
		$tax_fee=@$_GET['tax_fee'];#thuế vat
		$order_description=@$_GET['order_description:'];#chi tiết sản phẩm
		$payment_type=@$_GET['payment_type'];
		 $capnhat=update_db_baokim($order_id);
		   if($capnhat)
		   {
		   	
		   	
				     echo '<div align="center" style="background: none repeat scroll 0 0 #ECDEBC;
		    border: 1px solid #DFD6D3;
		    line-height: 20px;
		    padding: 15px;margin-top:20px; width:570px;"><h2>Cám ơn quý khách đã đặt phòng, quá trình thanh toán đã được hoàn tất.Chúng tôi đã gửi thông tin thuê phòng đến email của bạn đăng kí!</h2></div>';
				
  	       	     	echo '<tr>  <td class="col-1">   
                    	
                            <p class="title">';
  	       	     echo 'Thông Tin Phiên Giao Dịch';
  	       	     	echo '</p>
                         </td>
                    </tr>';
  	       	    echo '<tr><td rowspan="3" class="box col-1">                            
                            	<p>- Loại giao dịch: Thanh Toán Trực Tuyến</p>
                                <p>- Cổng Thanh Toán: Bảo Kim</p>
                                <p>- Mã Giao Dịch: '.$_GET['transaction_id'].'</p>
                                <p>- Loại Phòng: '.$_GET['order_description:'].'</p>
                                <p>- Số Tiền Thanh Toán: '.$_GET['total_amount'].'</p>
                                <p>- Loại Tiền Tệ: VND</p>
                        </td></tr>';
  	 
		                    	$orderid= $_GET['order_id'];
         	                    $user_id=get_userid_via_orderid($orderid);
         	                    $user_data=get_userdata($user_id);
         	                    $email=$user_data->user_email ;
         		                $s='Thông Tin Thuê Phòng';
								$m='<html body><h2>Thông Tin Thuê Phòng </h2><p><a target="blank" href="'.get_bloginfo('url').'/thong-tin-dat-phong?orderID='.$orderid .'&userID='. md5($user_id).'&option='.$user_id.'">Click Xem Thông Tin Thuê Phòng</a><p></body></html>';
								$headers = array(
					     	 	  'From: '.get_bloginfo('name').' <'.get_bloginfo('admin_email').'>',
					       			 "Content-Type: text/html"
					  			  );
					   			  $h = implode("\r\n",$headers) . "\r\n";
							  	  wp_mail($email, $s, $m,$h);
			
			         			return ;
		   }
			   else 
			   {
			 
			echo 'div align="center" style="background: none repeat scroll 0 0 #ECDEBC;
	    border: 1px solid #DFD6D3;
	    line-height: 20px;
	    padding: 15px;margin-top:20px; width:570px;"><h2>Có lỗi Xãy Ra Trong Quá Trình Cập Nhật Dữ Liệu!</h2></div>';
			
				return ;
		   }
		     
	    }
   }
}
function get_check_form_bk()
{
?>
   <form action="" method="post">
   <input type=image src="https://www.baokim.vn/application/uploads/buttons/btn_pay_now_3.png" />
   <?php wp_nonce_field('bao_kim__checkout','action_bao_kim_checkout');?>
   </form>


<?php 

}
function redirect_to_bao_kim($order_id, $total_amount, $shipping_fee, $tax_fee, $order_description, $url_detail)
{
     echo get_check_form_bk();
     if(wp_verify_nonce($_POST['action_bao_kim_checkout'],'bao_kim__checkout'))
     {
          check_submit_form_bk($order_id, $total_amount, $shipping_fee, $tax_fee, $order_description, $url_detail);
     }

}
function test_form_bao_kim($product_name,$order_id,$price,$product_description)
{
	$url_return=get_bloginfo('url').'baokim';
	$url_cancel=get_bloginfo('url').'cancel';
	$merchant_id=get_option('merchant_id_bk');
	$secure_pass=get_option('secure_pass_bk');
	 $email_bk=get_option('email_bk');
	  $querystring = 'http://sandbox.baokim.vn/payment/customize_payment/product';
	  $querystring .='?business='.urlencode($email_bk).'&';
	  $querystring .='product_name=' .urlencode($product_name).'&';
	  $querystring .='product_price=' .urlencode($price).'&';
	  $querystring .='total_amount='.urlencode($price).'&';
	  $querystring .='product_description='.urlencode($product_description);
	echo "<script>document.location.href='$querystring';</script>";
	exit();
	
}

function save_transaction_bao_kim_to_db($orderid,$payment_amount,$currency,$payment_type,$order_description)
{
   global $wpdb;
   $payments_table=$wpdb->prefix .'payments';
    $data=array(
    'id'=>0,
    'txnid'=>'',
    'sessionid'=>session_id(),
    'orderid'=>$orderid,
    'amount'=>$payment_amount,
    'status'=>'no',
    'currency'=>$currency,
    'payment_type'=>$payment_type,
    'transaction_infor' =>$order_description,
    'createdtime'=>time()+7*3600
    );
    $run=$wpdb->insert($payments_table,$data);
    
    if($run)
    {
        return TRUE;
    }
    return false;
}

function update_db_baokim($orderid)
{
        global  $wpdb;
        $payment_table=$wpdb->prefix .'payments'; 
        $transaction_id=@$_GET['transaction_id'];
        //$order_id=@$_GET['order_id'];#mã order
		$total_amount=@$_GET['total_amount'];#giá sản phẩm
		//$transaction_status=@$_GET['transaction_status'];
		$payment_type=@$_GET['payment_type'];
		$order_description=@$_GET['order_description'];
       $run=$wpdb->query("update {$payment_table} set txnid='{$transaction_id}',amount={$total_amount},status='yes',transaction_infor='{$order_description}' where orderid={$orderid}");
      if($run)
      {
         return true;
      }
      return TRUE;
}
	